<?php

namespace GuanChanghu\Library\Http\Controllers;


use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use JsonException;


/**
 * @author 管昌虎
 * Class DocumentController
 * @tag encryption free
 * @package GuanChanghu\Library\Http\Controllers
 * Created on 2022/4/9 16:56
 * Created by 管昌虎
 * Email guanchanghu626@163.com
 */
class DocumentController extends Controller
{
    /**
     * @param string $client
     * @param string $version
     * @return Application|Factory|View
     * @throws FileNotFoundException
     * @throws JsonException
     */
    public function apiDoc(string $client, string $version)
    {
        $this->environmentCheck();

        if (!Storage::disk('file')->exists("json/apiDoc/{$client}/{$version}.json")) {
            abort(4000, '没有生成此文档请联系开发人员');
        }

        $directory = 'json/apiDoc';
        $directoryLength = strlen($directory);

        $jsonFiles = Storage::disk('file')->allFiles($directory);

        $allDocs = [];

        foreach ($jsonFiles as $jsonFile) {
            if (Str::endsWith($jsonFile, '.json')) {
                $value = substr($jsonFile, $directoryLength, -5);
                $valueArray = explode("/", $value);
                $allDocs[] = [
                    'value' => $value,
                    'label' => $valueArray[1] . ' ' . $valueArray[2]
                ];
            }
        }

        $apiDoc = json_decode(Storage::disk('file')->get("json/apiDoc/{$client}/{$version}.json"), true, 512, JSON_THROW_ON_ERROR);

        return view('apiDoc.index', compact('apiDoc', 'client', 'version', 'allDocs'));
    }

    /**
     * @return Application|Factory|View
     */
    public function apiDocRule()
    {
        $this->environmentCheck();

        return view('apiDoc.rule');
    }

    /**
     * @return Application|Factory|View
     */
    public function apiDocUpload()
    {
        $this->environmentCheck();

        return view('apiDoc.upload');
    }

    /**
     * @return void
     */
    protected function environmentCheck(): void
    {
        if (!app()->environment('local')) {
            abort(4000, '不是开发环境不提供此方法');
        }
        if (!env('LOCAL_ENABLE_DOC', true)) {
            abort(4000, '开发环境已经关闭此方法');
        }
    }
}
